#include <queue>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;

class Solution
{
public:
    static int ladderLength(const string& beginWord, const string& endWord, vector<string>& wordList)
    {
        unordered_set<string> visit;
        unordered_set<string> hash(wordList.begin(), wordList.end());
        int ret = 1;
        queue<string> q;
        q.emplace(beginWord);
        visit.insert(beginWord);

        if(beginWord == endWord)    return 1;
        if(!hash.count(endWord))    return 0;

        while(!q.empty())
        {
            ret++;
            int sz = q.size();
            while(sz--)
            {
                string t = q.front();
                q.pop();
                for(int i=0; i<beginWord.size(); i++)
                {
                    string tmp = t;
                    for(char ch='a'; ch<='z'; ch++)
                    {
                        tmp[i] = ch;
                        if(hash.count(tmp) && !visit.count(tmp))
                        {
                            if(tmp == endWord)
                                return ret;
                            q.emplace(tmp);
                            visit.insert(tmp);
                        }
                    }
                }
            }
        }
        return 0;
    }
};